package com.guo.worktool.Controller;

import com.guo.worktool.common.comps.RedisUtil;
import com.guo.worktool.common.core.AjaxResult;
import com.guo.worktool.common.model.VisitorRecords;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundZSetOperations;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

/**
 * @program: WorkTool
 * @author: Mr.GUO
 * @create: 2023-03-21 21:15
 *
 * 添加用户使用排行榜
 **/
@Slf4j
@RestController
@CrossOrigin
public class VisitsController {

    private final String visitsKey = "visits:rank:daily";

    @Autowired
    private RedisUtil redisUtil;


    /**
     * 查询排行榜，从大到小排序
     * @return
     */
    @PostMapping("/visits/list/des")
    public AjaxResult getIpListdes(){
        BoundZSetOperations<String, Object> operations = redisUtil.zSetOperations(visitsKey);
        Set<Object> set = operations.reverseRange(0, -1);
        return AjaxResult.success(set);
    }


    /**
     * 查询排行榜，从小到大排序  升序
     * @return
     */
    @PostMapping("/visits/list/asc")
    public AjaxResult getIpListasc(){
        BoundZSetOperations<String, Object> operations = redisUtil.zSetOperations(visitsKey);
        Set<Object> set = operations.range(0, -1);
        return AjaxResult.success(set);
    }

    /**
     * 获取zset当前key下所有ip和score 升序
     * @return
     */
    @PostMapping("/visits/ipandscorelist/asc")
    public AjaxResult getIpAndScorelistAsc(){
        List<VisitorRecords> list = redisUtil.queryIpAndScoreAsc();
        log.info("getIpAndScorelistAsc:{}", list);
        return AjaxResult.success(list);
    }
    /**
     * 获取zset当前key下所有ip和score 降序
     * @return
     */
    @PostMapping("/visits/ipandscorelist/des")
    public AjaxResult getIpAndScorelistDes(){
        List<VisitorRecords> list = redisUtil.queryIpAndScoreDes();
        log.info("getIpAndScorelistDes:{}", list);
        return AjaxResult.success(list);
    }


    /**
     * 查询指定人员的排行
     * @return
     */
    @PostMapping("/visits/getByIp")
    public AjaxResult getListById(@RequestParam("ip") String ip){
        BoundZSetOperations<String, Object> operations = redisUtil.zSetOperations(visitsKey);
        Long rank = operations.reverseRank(ip);
        return AjaxResult.success(++rank);
    }
    /**
     * 积分添加
     * @return
     */
    @PostMapping("/visits/addscore")
    public AjaxResult addScoreByIp(@RequestParam("ip") String ip, @RequestParam("score") int score){
        Double aDouble = redisUtil.addScoreByIpMethod(ip, score, visitsKey);
        log.info("积分添加成功：{}，现在积分为：{}", ip, aDouble);
        return AjaxResult.success();
    }


}
